package http

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"mall-portalv2/global"
	"mall-portalv2/internal/model"
	"mall-portalv2/internal/server/ctx"
	"mall-portalv2/library/common"
	"net/http"
	"time"
)

func OrderDetailHandlerFunc(c *gin.Context) {
	app := ctx.Gin{C: c}

	uidStr, isUid := c.Get("uid")
	if !isUid {
		global.Log.Error("uid不存在")
		app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, nil)
		return
	}
	UID := common.Str2Int64(fmt.Sprintf("%d", uidStr))

	// 订单状态：-1->全部；0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭

	orderId := common.Str2Int64(c.Param("orderId"))

	result, err := svc.QueryOmsOrderWhereId(c, orderId, UID)
	if err != nil {
		global.Log.Error("查询失败", zap.Error(err))
		app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
		return
	}

	global.Log.Info("打印订单详情接口", zap.Any("result", result))

	tempNote, _ := base64.StdEncoding.DecodeString(result.Note)
	result.Note = string(tempNote)

	orderResult := model.OrderList{}
	reBt, _ := json.Marshal(result)
	json.Unmarshal(reBt, &orderResult)

	////	查询每一单下的商品详情
	orderItemResult, err := svc.QueryOmsItemAndProductWhereOrderId(c, orderId)
	if err != nil {
		global.Log.Error("查询失败", zap.Error(err))
		app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
		return
	}
	orderResult.OrderItemList = orderItemResult

	app.Response(http.StatusOK, ctx.OK, orderResult)
}

func OrderCancelHandlerFunc(c *gin.Context) {
	app := ctx.Gin{C: c}

	orderId := common.Str2Int64(c.Query("orderId"))

	uidStr, isUid := c.Get("uid")
	if !isUid {
		global.Log.Error("uid不存在")
		app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, nil)
		return
	}
	UID := common.Str2Int64(fmt.Sprintf("%d", uidStr))

	// 订单状态：-1->全部；0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭

	result, err := svc.QueryOmsOrderWhereId(c, orderId, UID)
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			app.Response(http.StatusOK, ctx.NO, err)
			return
		} else {
			global.Log.Error("订单状态查询失败", zap.Error(err))
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
			return
		}
	}

	// TODO: 修改订单,只有待付款或者待发货才可以取消订单
	if result.Status == 0 || result.Status == 1 {
		orderUpdates := make(map[string]interface{})
		orderUpdates["status"] = 4
		if err := svc.UpdateOrder(c, orderId, orderUpdates); err != nil {
			global.Log.Error("mysql err", zap.Error(err))
			return
		}

		// TODO: 恢复锁库存
		////	查询每一单下的商品详情
		//orderItemResult, err := svc.QueryOmsItemAndProductWhereOrderId(c, orderId)
		//if err != nil {
		//	global.Log.Error("查询失败", zap.Error(err))
		//	app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
		//	return
		//}

		if err := svc.UnLockOmsOrder(c, orderId); err != nil {
			global.Log.Error("mysql err", zap.Error(err))
			return
		}
		global.Log.Info("恢复锁掉的库存", zap.Any("result", result))

		app.Response(http.StatusOK, ctx.OK, nil)
		return
	} else {
		app.Response(http.StatusBadRequest, ctx.StatusBadRequest, "只有待付款或者待发货才可以取消订单")
		return
	}
}

func OrderConfirmReceiveHandlerFunc(c *gin.Context) {
	app := ctx.Gin{C: c}

	orderId := common.Str2Int64(c.Query("orderId"))

	uidStr, isUid := c.Get("uid")
	if !isUid {
		global.Log.Error("uid不存在")
		app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, nil)
		return
	}
	UID := common.Str2Int64(fmt.Sprintf("%d", uidStr))

	// 订单状态：-1->全部；0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭

	result, err := svc.QueryOmsOrderWhereId(c, orderId, UID)
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			app.Response(http.StatusOK, ctx.NO, err)
			return
		} else {
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
			return
		}
	}

	// TODO: 修改订单,只有已发货才可以确认收获
	if result.Status == 2 {
		orderUpdates := make(map[string]interface{})
		orderUpdates["status"] = 3
		orderUpdates["confirm_status"] = 1
		orderUpdates["receive_time"] = time.Now()
		if err := svc.UpdateOrder(c, orderId, orderUpdates); err != nil {
			global.Log.Error("mysql err", zap.Error(err))
			return
		}

		// TODO: 恢复锁库存

		//if err := svc.UnLockOmsOrder(c, orderId); err != nil {
		//	global.Log.Error("mysql err", zap.Error(err))
		//	return
		//}
		//
		//global.Log.Info("恢复锁掉的库存", zap.Any("result", result))

		app.Response(http.StatusOK, ctx.OK, nil)
		return
	} else {
		app.Response(http.StatusBadRequest, ctx.StatusBadRequest, "只有已发货才可以确认收货")
		return
	}
}

func OrderDeleteHandlerFunc(c *gin.Context) {
	app := ctx.Gin{C: c}

	orderId := common.Str2Int64(c.Query("orderId"))

	uidStr, isUid := c.Get("uid")
	if !isUid {
		global.Log.Error("uid不存在")
		app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, nil)
		return
	}
	UID := common.Str2Int64(fmt.Sprintf("%d", uidStr))

	// 订单状态：-1->全部；0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭

	result, err := svc.QueryOmsOrderWhereId(c, orderId, UID)
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			app.Response(http.StatusOK, ctx.NO, err)
			return
		} else {
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
			return
		}
	}

	// TODO: 修改订单,只有订单完成或者订单关闭才可以删除
	if result.Status == 4 || result.Status == 3 {
		orderUpdates := make(map[string]interface{})
		orderUpdates["delete_status"] = 1
		if err := svc.UpdateOrder(c, orderId, orderUpdates); err != nil {
			global.Log.Error("mysql err", zap.Error(err))
			return
		}
		// TODO: 把该订单下的状态改成8
		orderReturnUpdates := make(map[string]interface{})
		orderReturnUpdates["status"] = 8
		if err := svc.UpdateOmsOrderReturnApplyWhereOrderId(c, orderId, orderReturnUpdates); err != nil {
			global.Log.Error("订单退款修改失败", zap.Error(err))
			return
		}
		app.Response(http.StatusOK, ctx.OK, nil)
		return
	} else {
		app.Response(http.StatusBadRequest, ctx.StatusBadRequest, "只有订单完成或者订单关闭才可以删除")
		return
	}
}
